package main

import (
	"fmt"
	"github.com/google/gopacket"
	"github.com/google/gopacket/layers"
	"github.com/google/gopacket/pcap"
	"net"
	"time"
)

var h *pcap.Handle

func main() {
	h, err := pcap.OpenLive(
		"\\\\Device\\\\NPF_{C6571165-98E0-458B-B665-61F7D78A00CE}", // network device
		int32(65535),
		true,
		time.Microsecond,
	)
	if err != nil {
		panic(err)
	}
	err = h.SetBPFFilter("tcp and dst host 180.101.49.11")
	if err != nil { // optional
		panic(err)
	}

	go func() {
		time.Sleep(time.Second * 10)

		err := h.SetBPFFilter("tcp")
		if err != nil {
			return
		}
	}()

	go func() {
		time.Sleep(time.Second * 20)

		err := h.SetBPFFilter("tcp and dst host 180.101.49.11")
		if err != nil {
			return
		}
	}()

	defer h.Close()
	for true {
		sendPacket()
	}
}

func sendPacket() error {

	smac, err2 := net.ParseMAC("80:05:88:3c:56:3a")
	if err2 != nil {
		panic(err2)
	}
	dmac, err3 := net.ParseMAC("B4:69:21:8A:58:72")
	if err3 != nil {
		panic(err2)
	}

	eth := layers.Ethernet{
		SrcMAC: smac,
		DstMAC: dmac,
	}

	ipv4 := layers.IPv4{
		SrcIP:    net.ParseIP("192.168.30.22"),
		DstIP:    net.ParseIP("192.168.7.45"),
		Protocol: layers.IPProtocolTCP,
	}

	tcp := layers.TCP{
		SrcPort: layers.TCPPort(666),
		DstPort: layers.TCPPort(22),
		Ack:     10000,
		RST:     true,
	}

	options := gopacket.SerializeOptions{
		FixLengths:       true,
		ComputeChecksums: true,
	}

	if err := tcp.SetNetworkLayerForChecksum(&ipv4); err != nil {
		panic(err)
	}
	buffer := gopacket.NewSerializeBuffer()

	err := gopacket.SerializeLayers(buffer, options, &eth, &ipv4, &tcp)
	if err != nil {
		panic(err)
	}
	err = h.WritePacketData(buffer.Bytes())
	if err != nil {
		return err
	}
	fmt.Println("3srcIp: ", ipv4.SrcIP.String(), "dstIp: ", ipv4.DstIP.String())
	fmt.Println("3srcMac: ", eth.SrcMAC.String(), "dstMac: ", eth.DstMAC.String())
	return nil
}
